package com.sslite.reports;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;

import com.sslite.model.MetaData;
import com.sslite.reports.dailyvolumeaggregatereport.DailyVolumeAggregateReportRunnerImpl;
import com.sslite.reports.effectsofhighvolumereport.EffectsOfHighVolumeReportRunnerImpl;
import com.sslite.util.SSLiteProperties;
import com.sslite.util.Utility;

public class ReportController {

	private String getHeader(){
		final StringBuilder sbHead = new StringBuilder();
		sbHead.append( "<head>\n" );
		sbHead.append( "<script>\n" );
		sbHead.append( "function showIntraDayDetails(appletName){\n" );
		sbHead.append( "	chrt = document[appletName].chart;\n" );
		sbHead.append( "	selectedIndex = chrt.getLastSelectedSample();\n" );
		sbHead.append( "	if( selectedIndex != -1 ){\n" );
		sbHead.append( "		symbol = chrt.getTitle();\n" );
		sbHead.append( "		sample0 = chrt.getChartData().getSample(0, selectedIndex);\n" );
		sbHead.append( "		fileName = './snapshot/' +symbol+'/'+symbol+ '_'+ sample0.getLabel().replace(/\\//g, '_')+ '.html';\n" );
		sbHead.append( "		window.open(fileName, '_intraDaySnapshot', 'width=830,height=600,scrollbars,resizable')\n" );
		sbHead.append( "	}else{\n" );
		sbHead.append( "		alert('Please make a selection in Chart.');\n" );
		sbHead.append( "	}\n" );
		sbHead.append( "}\n" );
		sbHead.append( "</script>\n" );
		sbHead.append( "</head>\n" );
		return sbHead.toString();
	}
	
	public void generateReports(final List<MetaData> metaDataList) throws Exception{
		if( SSLiteProperties.RPT_DAILYVOLUMEAGGREGATE_GENERATE.getValue() != null && SSLiteProperties.RPT_DAILYVOLUMEAGGREGATE_GENERATE.getValue().equals("true") ){
			generateAndClubReports(new DailyVolumeAggregateReportRunnerImpl(metaDataList), SSLiteProperties.RPT_PATH_DAILYVOLUMEAGGREGATE.getValue(), SSLiteProperties.RPT_PATH_DAILYVOLUMEAGGREGATE_QUALIFIED.getValue(), SSLiteProperties.TMP_RPT_FOLDER_DAILYVOLUMEAGGREGATE.getValue());
		}
		
		if( SSLiteProperties.RPT_EFFECTSOFHIGHVOLUME_GENERATE.getValue() != null && SSLiteProperties.RPT_EFFECTSOFHIGHVOLUME_GENERATE.getValue().equals("true") ){
			generateAndClubReports(new EffectsOfHighVolumeReportRunnerImpl(metaDataList), SSLiteProperties.RPT_PATH_EFFECTSOFHIGHVOLUME.getValue(), SSLiteProperties.RPT_PATH_EFFECTSOFHIGHVOLUME_QUALIFIED.getValue(), SSLiteProperties.TMP_RPT_FOLDER_EFFECTSOFHIGHVOLUME.getValue());
		}
	}
	
	private void generateAndClubReports(final IReportRunner iReport, final String rptPathAll, final String rptPathQualified, final String tmpRptFolder) throws Exception{
		Writer bwAll = null;
		Writer bwQualified = null;
		
		try{
			bwAll = new BufferedWriter( new FileWriter(rptPathAll) );
			bwQualified = new BufferedWriter( new FileWriter(rptPathQualified) );
			
			final String sbHead = getHeader();
			bwAll.append( sbHead ).append( "<body><pre>\n" );
			bwQualified.append( sbHead ).append( "<body><pre>\n" );
			
			// Cleanup old reports.
			for( final File rptFile : new File(tmpRptFolder).listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File arg0, String arg1) {
					return arg1.endsWith(".html");
				}
			})){
				System.out.println( "ReportController: Deleting " +rptFile.getAbsolutePath() );
				rptFile.delete();
			}
			
			long start = System.currentTimeMillis();
			boolean reportGenerated = iReport.generateReport();
			long end = System.currentTimeMillis();
			
			if( reportGenerated ){
				final File[] qualifiedRpts = new File(tmpRptFolder).listFiles(new FilenameFilter(){
					@Override
					public boolean accept(File arg0, String arg1) {
						return arg1.startsWith("q_") && arg1.endsWith(".html");
					}
				});
				
				final File[] allRpts = new File(tmpRptFolder).listFiles(new FilenameFilter(){
					@Override
					public boolean accept(File arg0, String arg1) {
						return arg1.endsWith(".html");
					}
				});
				final List<File> qualifiedRptsFileList = Arrays.asList( qualifiedRpts );
				for( final File file : allRpts ){
					String symbol = file.getName();
					symbol = symbol.substring( symbol.indexOf("_")+1, symbol.indexOf(".") ).trim();
					
					if( qualifiedRptsFileList.contains( file ) ){
						bwQualified.append( Utility.getContent( file.toURL().toString() ) ).append("<BR>");
					}
					
					bwAll.append( Utility.getContent( file.toURL().toString() ) ).append("<BR>");
				}
				
				System.out.println( "ReportController: Report generated in " +Utility.round(( (double)(end - start)/1000.0)/60.0)+ " mins @ " +rptPathQualified );
			}else{
				final String errorMsg = "<font color=red>Report process timed out. You may want to tweak rpt.thread.pool in sslite.properties</font>";
				bwAll.append( errorMsg );
				bwQualified.append( errorMsg );
			}
			
			bwAll.append( "</pre></body></html>" );
			bwQualified.append( "</pre></body></html>" );
		}
		finally{
			if( bwAll != null ){
				bwAll.close();
			}
			if( bwQualified != null ){
				bwQualified.close();
			}
		}
	}
}
